<template>
	<view class="search-outer-wrapper">
		<div class="fixed">
			<div class="search-wrapper">
				<div class="type-change" @click="showTypeChoose">
					<span>{{typeSelect}}</span>
					<u-icon v-if="typeShow" name="arrow-up" size="24" color="#999"></u-icon>
					<u-icon v-else name="arrow-down" size="24" color="#999"></u-icon>
				</div>
				<u-search class="search" v-model="keyword" :clearabled='false' :show-action="false" bg-color="#ffffff"
					@search="doSearch(faslse)" @focus='focus' @blur='blur' placeholder="搜索"
					style="z-index: 9999999;width: 100%;">
				</u-search>
			</div>
			<div class="type-choose" @click="hideTypeChoose" v-if="typeShow">
				<div class="content-box" @click.stop>
					<div class="item" @click="chooseType('商品',keyword)">商品</div>
					<div class="item" @click="chooseType('店铺',keyword)">店铺</div>
				</div>
			</div>
			<u-popup v-model="showSearch" mode="top" width='100%' :mask="false">
				<view class="popup-search">
					<view class="search">搜索热词</view>
					<view class="searchList">
						<u-button v-for="(item,index) in searchList" :key="index" size="mini"
							:custom-style="searchStyle" @click="hotWord(item)">{{item}}
						</u-button>
					</view>
				</view>
			</u-popup>

			<view class="navbar-wrapper">
				<view class="nav-item" :class="{ current: filterIndex === 3 }" @click="tabClick(3, '销量')">
					<text class="name">按销量</text>
					<view class="p-box">
						<u-icon size="13" name="play-right-fill" class="down"
							:color="params.type === '销量' && params.order === 'desc'?'#e63214':'#999999'">
						</u-icon>
					</view>
				</view>
				<view class="nav-item" :class="{ current: filterIndex === 4 }" @click="priceClick(4,'价格降')">
					<text class="name">按价格</text>
					<view class="p-box">
						<u-icon size="13" name="play-right-fill" class="down"
							:color="params.type === '价格降' && params.order === 'desc'?'#e63214':'#999999'">
						</u-icon>
					</view>
					<u-popup v-model="show" mode="top" width=100% :mask="false" :mask-close-able="false">
						<view class="popup-box">
							<view class="popup-item" @click="priceSearch(1,'价格降')"
								:class="{ current: priceIndex === 1 }">
								价格降序
							</view>
							<view class="popup-item" @click="priceSearch(2,'价格升')"
								:class="{ current: priceIndex === 2 }">
								价格升序
							</view>
							<u-form :model="params" ref="params">
								<view class='popup-item popup-text'>
									<text :class="{ current: priceIndex === 3 }">筛选</text>
									<view class='popup-input'>
										<u-input class='input' @click="priceSearch(3)" v-model="params.startPrice"
											:type="type" :border="border" placeholder-style='font-size: 22rpx;'
											placeholder="自定义最低价" />
										——
										<u-input class='input' @click="priceSearch(3)" v-model="params.endPrice"
											:type="type" :border="border" placeholder-style='font-size: 22rpx;'
											placeholder="自定义最高价" />
									</view>
								</view>

								<view class="popup-but">
									<u-button type="info" shape="circle" :custom-style="customStyle"
										@click="cancelClick('params')">取消</u-button>
									<u-button type="success" shape="circle" :custom-style="affirmStyle"
										@click="submitClick()">确认</u-button>
								</view>
							</u-form>
						</view>
					</u-popup>
				</view>
				<view class="nav-item" :class="{ current: filterIndex === 6 }" @click="tabClick(6, '评分')">
					<text class="name">按评分</text>
					<view class="p-box">
						<u-icon size="13" name="play-right-fill" class="down"
							:color="params.type === '评分' && params.order === 'desc'?'#e63214':'#999999'">
						</u-icon>
					</view>
				</view>
			</view>
		</div>
		<!-- 搜索 -->
		<view class="goods-content">
			<div v-if="goodsList===''">
				<u-loadmore bg-color="transparent" status="loading" icon-type="flower" />
			</div>
			<div v-else-if="goodsList.length==0">
				<u-empty text="暂无数据" mode="list"></u-empty>
			</div>
			<div v-else>
				<scroll-view scroll-anchoring enableBackToTop="true" @scrolltolower="loadmore()" scroll-with-animation
					scroll-y lower-threshold="250" class="scoll-page">
					<view class="goods-list">
						<view v-for="(item, index) in goodsList" :key="index" class="goods-item">
							<div @click="navigateToDetailPage(item)">
								<view class="image-wrapper">
									<image :src="item.thumbnail" mode="aspectFill"></image>
								</view>
								<view class="goods-detail">
									<div class="title clamp text-hidden">
										{{ item.goodsName }}
									</div>
									<div class='evaluate'>
										<span class='grade'>{{item.score||0.0}}分</span>
										<span class='sales'> 月售 {{item.monthSales ||0}}+ </span>
									</div>
									<view class="price-box">
										<span class="money">
											<span>{{ formatPrice(item.memberPrice)[0] }}</span>
											<span>.</span>
											<span>{{ formatPrice(item.memberPrice)[1] }}</span>
										</span>
									</view>
								</view>
							</div>
						</view>
					</view>
					<uni-load-more :status="loadingType"></uni-load-more>
				</scroll-view>
			</div>
		</view>
	</view>
</template>


<script>
	import {
		getGoodsList,
		getGoodsRelated,
		getShopList,
		hotWordSearch
	} from "@/api/goods.js"

	import {
		getHotKeywords
	} from "@/api/home.js"
	import storage from "@/utils/storage"
	export default {
		data() {
			return {
				typeShow: false,
				typeSelect: '商品', // 查询类型  商品还是店铺
				showSearch: false, //搜索热词弹框
				searchList: [], //热词数据
				//按价格取消按钮样式
				customStyle: {
					border: "2 rpx solid rgba(245, 227, 220, 1)",
					color: "rgba(255, 148, 110, 1)",
					fontSize: "26rpx",
				},
				//按价格确认按钮样式
				affirmStyle: {
					backgroundColor: "rgba(255, 148, 110, 1)",
					color: 'rgba(255, 255, 255, 1)',
					fontSize: "26rpx",
				},
				//搜索热词
				searchStyle: {
					marginRight: '15rpx', // 注意驼峰命名，并且值必须用引号包括，因为这是对象
					marginBottom: '15rpx',
				},
				show: false,
				keyword: "",
				goodsList: [],
				loadingType: "loading", //加载更多状态
				filterIndex: 0, //条件高亮
				priceIndex: 1, //按价格条件高亮
				params: {
					pageNumber: 1,
					pageSize: 10,
					keyword: "",
					type: '', //筛选类型
					startPrice: '', //自定义最低价
					endPrice: '', //自定义最高价
				},
				sortParams: {
					pageNumber: 1,
					pageSize: 10,
					categoryId: "",
				},
			}
		},
		onLoad(options) {
			console.log("$$$", options)
			// if (options.keyword != '' && options.keyword) {
			// 	this.keyword = options.keyword
			// 	this.doSearch(options.keyword)
			// }
			if (options.category) {
				this.params.categoryId = options.category
				this.sortParams.categoryId = options.category
				uni.setNavigationBarTitle({
					title: options.name
				})
			} else {
				uni.setNavigationBarTitle({
					title: '搜索商品'
				})
			}
			if (options.storeId) {
				this.params.storeId = options.storeId
			}
			if (options.keyword) {
				this.keyword = options.keyword
				this.params.keyword = options.keyword
			}
			this.loadData()
		},
		onReachBottom() {
			this.params.pageNumber++
			this.loadData()
		},
		methods: {
			showTypeChoose() {
				this.typeShow = true
			},
			hideTypeChoose() {
				this.typeShow = false
			},
			chooseType(type, keyword) {
				// this.typeSelect = type
				// this.$emit("typeChange", type)
				this.hideTypeChoose()
				if (type == '店铺') {
					uni.redirectTo({
						url: `/pages/search/store?keyword=${keyword}`,
					});
				}
			},
			//热词跳转
			hotWord(item) {
				this.showSearch = false
				this.keyword = item
				this.doSearch()
			},
			//价格刷选取消
			cancelClick(params) {
				this.$set(this.params, "type", '')
				this.$set(this.params, "startPrice", "")
				this.$set(this.params, "endPrice", "")
				this.show = false
			},
			//价格筛选确认
			submitClick() {
				this.initParams()
				this.show = false
				this.loadData("refresh", 1)
			},
			//按价格分类型
			priceSearch(i, type) {
				if (i == 3) {
					this.priceIndex = i
					this.$set(this.params, "type", "")
				} else {
					this.priceIndex = i
					this.$set(this.params, "type", type)
					this.$set(this.params, "startPrice", "")
					this.$set(this.params, "endPrice", "")
				}
			},
			//按价格弹框弹出高亮
			priceClick(index, type) {
				this.show = true
				this.filterIndex = index
				this.params.order = "desc"
				this.$set(this.params, "type", type)
			},
			initParams() {
				this.loadingType = "loading"
				this.goodsList = ''
				this.params.pageNumber = 1
				this.params.pageSize = 10
			},
			// 格式化金钱  1999 --> [1999,00]
			formatPrice(val) {
				if (typeof val == "undefined" || !val) {
					return val
				}
				return val.toFixed(2).split(".")
			},
			// 跳转到商品详情
			navigateToDetailPage(item) {
				uni.navigateTo({
					url: `/pages/product/goods?id=${item.skuList[0].id}&goodsId=${item.id}`,
				})
			},
			// 跳转到店铺
			navigateToshop(item) {
				uni.navigateTo({
					url: `/pages/product/shopPage?id=${item.id}`,
				})
			},
			// 跳转地址
			navigateToStoreDetailPage(item) {
				uni.navigateTo({
					url: `/pages/product/shopPage?id=${item.storeId}`,
				})
			},
			tabClick(index, type) {
				this.initParams()
				this.params.order = "desc"
				this.$set(this.params, "type", type)
				if (index == 0) {
					this.params.sort = "releaseTime"
					this.params.order = "desc"
				}

				this.filterIndex = index
				this.loadData("refresh", 1)
				uni.showLoading({
					title: "正在加载",
				})
			},
			/**
			 * 加载热门搜索
			 * 1.5分钟之后更新缓存
			 * 2.如果有缓存热门关键字则去请求缓存
			 */
			async loadHotKeyword() {
				this.hotKeywordList = []
				if (
					!storage.getHotWords().time ||
					storage.getHotWords().time <= new Date().getTime() / 1000
				) {
					// 没有缓存或者第一次进入请求接口保存缓存
					let res = await getHotKeywords(10)
					let keywords = res.data.result

					keywords.forEach((item) => {
						this.hotKeywordList.push(item)
					})

					let hotData = {
						time: new Date().getTime() / 1000 + 30 * 5,
						keywords: keywords,
					}
					storage.setHotWords(hotData)
				} else {
					let keywords = storage.getHotWords().keywords

					keywords.forEach((item) => {
						this.hotKeywordList.push(item)
					})
				}
			},
			//加载商品 ，带下拉刷新和上滑加载
			async loadData(type, loading) {
				if (type === "refresh") {
					this.initParams()
				}
				if (this.loadingType === "noMore") return
				let goodsList = await getGoodsList(this.params)

				let list = goodsList.data.result.records
				this.afterList(list)
				uni.hideLoading()
			},
			afterList(list) {
				if (this.goodsList === '') {
					this.goodsList = []
				}
				if (list.length < 10) {
					this.loadingType = "noMore"
				}
				this.goodsList = this.goodsList.concat(list)
			},
			//搜索获取焦点
			focus() {
				this.typeShow = false
				this.showSearch = !this.showSearch
				hotWordSearch().then((res) => {
					if (res.data.success) {
						this.searchList = res.data.result
					} else {
						this.searchList = []
					}
				})
			},
			//搜索获失去焦点
			blur() {
				this.showSearch = false
			},
			/**
			 * 执行搜索
			 */
			doSearch(keyword) {
				this.showSearch = false
				this.params.keyword = this.keyword
				this.$set(this.sortParams, "keyword", keyword)
				this.loadData("refresh", 1)
			},
		},
	};
</script>

<style lang="scss" scoped>
	/deep/ .popup-search {
		margin-top: 105upx !important;
	}

	/deep/ .popup-box {
		margin-top: 170upx !important;
	}

	/deep/ .u-drawer-top {
		background-color: transparent !important;
	}



	.search-outer-wrapper {
		padding-top: 190upx;
		padding-bottom: 32upx;

		.fixed {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 99;
			background-color: rgba(240, 243, 248, 1);

			.type-choose {
				position: fixed;
				top: 0;
				left: 0;
				bottom: 0;
				right: 0;
				background-color: transparent;
				z-index: 99;

				.content-box {
					position: fixed;
					top: 95upx;
					left: 13upx;
					width: 190upx;
					background-color: #333;
					z-index: 100;
					border-radius: 12upx;

					&::before {
						content: " ";
						position: absolute;
						top: -8upx;
						left: 80upx;
						width: 20upx;
						height: 20upx;
						transform: rotate(45deg);
						background-color: #333;
					}

					.item {
						height: 100upx;
						line-height: 100upx;
						color: #fff;
						border-bottom: 2upx solid #444;
						text-align: center;

						&:last-child {
							border: none;
						}
					}
				}
			}
		}

		.search-wrapper {
			padding: 0 24upx;
			display: flex;
			// justify-content: center;

			.type-change {
				padding: 0 24upx;
				flex: 0 0 140upx;
				display: flex;
				justify-content: space-around;
				align-items: center;
			}
		}

		.navbar-wrapper {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 60rpx;
			z-index: 10;

			.nav-item {
				flex: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				height: 100%;
				font-size: 26rpx;
				color: #242424;
				position: relative;

				.p-box {
					height: 36upx;
					display: flex;
					flex-direction: column;
					justify-content: space-around;

					.top {
						transform: rotate(-90deg);
					}

					.down {
						transform: rotate(90deg);
					}
				}

				.name {
					margin-right: 8upx;
				}
			}

			.current {
				color: #e63214;
				position: relative;
			}
		}
	}

	.search-outer-wrapper {
		.search {
			margin: 25upx 0;
			font-weight: 700;
			font-size: 32upx;
		}

		.searchList {
			margin-bottom: 20upx;
		}

		.popup-search {
			padding: 30rpx 45upx;
			background-color: #ffffff;
		}

		.popup-box {
			padding: 0 45upx;
			background-color: #ffffff;

			.popup-item {
				padding-bottom: 36upx;
				padding-top: 32upx;
				border-bottom: 2rpx solid rgba(237, 237, 237, 1);
				font-size: 26upx;
				color: #000;
			}

			.current {
				color: #e63214;
			}

			.popup-text {
				display: flex;
				align-items: center;

				.popup-input {
					margin-left: 79upx;
					display: flex;
					align-items: center;

					.input {
						background-color: rgba(237, 235, 235, 1);
						font-size: 22upx;
						width: 174upx;
						border-radius: 30rpx;
						padding: 0 10upx;
					}
				}
			}

			.popup-but {
				width: 100%;
				display: flex;
				justify-content: space-around;
				margin-top: 36upx;
				padding-bottom: 36upx;
			}
		}

		.goods-list {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			padding: 0 24upx 32upx 24upx;
			width: 100%;

			.goods-item {
				flex: 0 0 340upx;
				background-color: #ffffff;
				display: flex;
				border-radius: 16rpx;
				flex-direction: column;
				margin-bottom: 20rpx;
				padding-bottom: 20rpx;
				width: 0;

				.goods-detail {
					margin: 0 20rpx;
				}
			}

			.image-wrapper {
				width: 100%;
				height: 330rpx;
				border-radius: 16rpx 16rpx 0 0;
				overflow: hidden;
				padding: 0;

				image {
					width: 100%;
					height: 100%;
					opacity: 1;
					border-radius: 16rpx 16rpx 0 0;
				}
			}

			.title {
				font-size: $font-base;
				color: $font-color-dark;
				line-height: 1.5;
				height: 60rpx;
				padding: 10rpx 0 0;
				display: -webkit-box;

				-webkit-box-orient: vertical;

				-webkit-line-clamp: 2;

				overflow: hidden;
			}

			.text-hidden {
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.evaluate {
				display: flex;
				justify-content: space-between;

				.grade {
					color: rgba(255, 137, 33, 1);
					font-size: 26upx;
				}

				.sales {
					color: rgba(173, 170, 170, 1);
					font-size: 24upx;
				}
			}

			.price-box {
				display: flex;
				align-items: center;

				.image {
					width: 24upx;
					height: 28upx;
					margin-right: 8upx;
				}

				.money {
					color: rgba(230, 50, 20, 1);
				}
			}
		}
	}
</style>
